package com.ruoyi.business.service.wecom.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.business.domain.dto.admin.wecom.WecomExternalContactFollowUserPageQueryDTO;
import com.ruoyi.business.domain.wecom.TbWecomExternalContactFollowUser;
import com.ruoyi.business.mapper.wecom.TbWecomExternalContactFollowUserMapper;
import com.ruoyi.business.service.wecom.ITbWecomExternalContactFollowUserService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpExternalContactService;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpUser;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class TbWecomExternalContactFollowUserServiceImpl extends ServiceImpl<TbWecomExternalContactFollowUserMapper, TbWecomExternalContactFollowUser> implements ITbWecomExternalContactFollowUserService {

    @Resource
    private WxCpService wxCpService;

    @Value("${wechat.cp.apps[0].agent-id}")
    private String agentId;

    @Override
    public TableDataInfo<TbWecomExternalContactFollowUser> sysPageQuery(WecomExternalContactFollowUserPageQueryDTO pageQueryDTO, PageQuery pageQuery) {
        LambdaQueryWrapper<TbWecomExternalContactFollowUser> qwl = Wrappers.lambdaQuery(TbWecomExternalContactFollowUser.class)
            .eq(StringUtils.isNotEmpty(pageQueryDTO.getUserId()), TbWecomExternalContactFollowUser::getUserId, pageQueryDTO.getUserId())
            .like(StringUtils.isNotEmpty(pageQueryDTO.getUserName()), TbWecomExternalContactFollowUser::getUserName, pageQueryDTO.getUserName())
            .orderByDesc(TbWecomExternalContactFollowUser::getCreateTime);
        Page<TbWecomExternalContactFollowUser> page = this.page(pageQuery.build(), qwl);
        return TableDataInfo.build(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean sysSyncWecomExternalContactFollowUserData() {
        WxCpExternalContactService externalContactService = wxCpService.getExternalContactService();
        List<String> wecomExternalContactFollowUserList = null;
        try {
            wecomExternalContactFollowUserList = externalContactService.listFollowers();
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
        List<TbWecomExternalContactFollowUser> insertList = new ArrayList<>();
        List<TbWecomExternalContactFollowUser> updateList = new ArrayList<>();
        for (String userId : wecomExternalContactFollowUserList) {
            // 根据 userId 获取人员详情
            WxCpUser wxCpUser = null;
            try {
                wxCpUser = wxCpService.getUserService().getById(userId);
            } catch (WxErrorException e) {
                throw new RuntimeException(e);
            }

            // 查询数据库是否已存在该记录
            TbWecomExternalContactFollowUser existingRecord = this.getOne(
                Wrappers.lambdaQuery(TbWecomExternalContactFollowUser.class)
                    .eq(TbWecomExternalContactFollowUser::getUserId, userId)
                    .eq(TbWecomExternalContactFollowUser::getAgentId, agentId)
            );

            if (ObjectUtils.isEmpty(existingRecord)) {
                // 不存在，新增
                TbWecomExternalContactFollowUser newEntity = new TbWecomExternalContactFollowUser();
                newEntity.setId(IdWorker.getId());
                newEntity.setAgentId(agentId);
                newEntity.setUserId(userId);
                newEntity.setUserName(wxCpUser.getName());
                newEntity.setCreateTime(new Date());
                insertList.add(newEntity);
            } else {
                // 存在，更新
                existingRecord.setUserName(wxCpUser.getName());
                // 如果需要更新其他字段，可以在这里添加
                existingRecord.setUpdateTime(new Date()); // 如果有更新时间字段
                updateList.add(existingRecord);
            }
        }
        // 批量处理
        boolean insertSuccess = true;
        boolean updateSuccess = true;
        if (CollectionUtils.isNotEmpty(insertList)) {
            insertSuccess = this.saveBatch(insertList);
        }
        if (CollectionUtils.isNotEmpty(updateList)) {
            updateSuccess = this.updateBatchById(updateList);
        }
        return insertSuccess && updateSuccess;
    }
}
